package com.tanhua.management.service;

import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import com.alibaba.dubbo.config.annotation.Reference;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tanhua.common.mapper.UserInfoMapper;
import com.tanhua.common.pojo.UserInfo;
import com.tanhua.dubbo.server.api.MessageDetailApi;
import com.tanhua.dubbo.server.api.MomentsApi;
import com.tanhua.dubbo.server.pojo.Comment;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import com.tanhua.management.vo.*;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
public class MessagesPagesService {

    @Reference(version = "1.0.0")
    private MessageDetailApi messageDetailApi;
    @Autowired
    private UserInfoMapper userInfoMapper;

    @Reference(version = "1.0.0")
    private MomentsApi momentsApi;

    @Autowired
     private  MessageDetailService messageDetailService;

    /**
     * 查询所有动态 封装一个MessagePageResult 用于返回给前端数据
     * MessagePageResult 实现的思路就是   去拼凑前端需要的数据 对象
     * @param messageParam
     * @return
     */
    public MessagePageResult queryMessages(MessageParam messageParam) {
        Integer paramUid = messageParam.getUid();
        if (ObjectUtil.isNotEmpty(paramUid)){
            MessagePageResult pageResult = new MessagePageResult();
            List<MessageResult> messageResultList = new ArrayList<>();
            PageInfo<Publish> pageInfo = momentsApi.findOneUserPublish(Convert.toLong(paramUid), messageParam.getPage(), messageParam.getPagesize());
            List<Publish> publishList = pageInfo.getRecords();
            for (Publish publish : publishList) {
                MessageResult messageResult =new MessageResult();
                messageResult.setId(publish.getId().toHexString());
                messageResult.setUserId(Convert.toInt(publish.getUserId()));
                messageResult.setCreateDate(publish.getCreated());
                messageResult.setText(publish.getText());
                messageResult.setMedias(publish.getMedias());
                messageResult.setState(publish.getState());
                messageResult.setCommentCount(momentsApi.findPublishCommentCount(messageResult.getId()));
                messageResult.setLikeCount(Convert.toInt(momentsApi.findLoveCount(messageResult.getId())));


                Integer publishRepoertCount = momentsApi.findPublishRepoertCount(messageResult.getId());
                messageResult.setReportCount(publishRepoertCount);
                Integer publishForwardCount = momentsApi.findPublishForwardCount(messageResult.getId());
                messageResult.setForwardingCount(publishForwardCount);



                QueryWrapper<UserInfo> wrapper = new QueryWrapper<>();
                wrapper.eq("user_id",messageResult.getUserId());
                UserInfo userInfo = userInfoMapper.selectOne(wrapper);

                messageResult.setNickName(userInfo.getNickName());
                messageResult.setUserLogo(userInfo.getLogo());

                messageResultList.add(messageResult);
            }

            // 6. 排序
            Collections.sort(messageResultList, (o1, o2) -> {
                int result = 0;
                switch (messageParam.getSortProp()) {
                    case "reportCount": {
                        result = o1.getReportCount() - o2.getReportCount();
                        break;
                    }
                    case "likeCount": {
                        result = o1.getLikeCount() - o2.getLikeCount();
                        break;
                    }
                    case "commentCount": {
                        result = o1.getCommentCount() - o2.getCommentCount();
                        break;
                    }
                    case "forwardingCount": {
                        result = o1.getForwardingCount() - o2.getForwardingCount();
                        break;
                    }
                    case "createDate": {
                    }
                    default: {
                        result = (int) (o1.getCreateDate() - o2.getCreateDate());
                        break;
                    }
                }
                if ("descending".equals(messageParam.getSortOrder())) {
                    result = -result;
                }
                return result;
            });


            pageResult.setPage(messageParam.getPage());
            pageResult.setPagesize(messageParam.getPagesize());
            pageResult.setCounts(publishList.size());//总条数
            Integer pageTotalNum = publishList.size() % pageResult.getPagesize() == 0 ? publishList.size() / pageResult.getPagesize() : publishList.size() / pageResult.getPagesize() + 1;
            pageResult.setPages(pageTotalNum);//总页数
            pageResult.setItems(messageResultList);
            return pageResult;
        }


        //拿出分页数据
        Integer page = messageParam.getPage();
        Integer pagesize = messageParam.getPagesize();
        //判断 先给出个默认页数
        if (!ObjectUtil.isAllNotEmpty(page, pagesize)) {
            page = 1;
            pagesize = 10;
        }
        //用户id
//        Integer uid = messageParam.getUid();
        //前端传来的id 就是 后面模糊查询要的id
        Integer LikeUserId = messageParam.getId();

        //从对象中拿出状态数据 ,前端传来的是默认"3" 审核状态
        Integer uid = messageParam.getUid();
        String state = messageParam.getState();
        //开始 和结束时间
        Long ed = messageParam.getEd();
        Long sd = messageParam.getSd();

        //将拿过来的分页数据设置给它
        MessagePageResult messagePageResult = new MessagePageResult();
        messagePageResult.setPage(page);
        messagePageResult.setPagesize(pagesize);


        /**
         * 创建一个分页的对象 (主要就是查询publish表)
         *  下面写的是四种情况进行查询
         *   likeUserId 空  sd,ed空:  查询这个时间段内 所有用户的动态
         *   likeUserId 不空  sd,ed空: 查询这个用户的 所有动态
         *   likeUserId 不空  sd,ed不空: 查询这个用户的 在某个时间段内的所有动态
         *   likeUserId 空  sd,ed空:  查询所有的动态
         */
        PageInfo<Publish> pageInfo = new PageInfo<>();
        if (LikeUserId != null && (ed < 0L && sd < 0L)) {
            //有id 没有日期
            System.out.println("uid = " + LikeUserId + ",sd = " + sd + ",ed= " + ed);
            pageInfo = messageDetailApi.queryPublishByUserId(messageParam.getPage(), messageParam.getPagesize(), messageParam.getSortOrder(), LikeUserId, state);
            messagePageResult = this.queryMethod(LikeUserId, state, pagesize, messagePageResult, pageInfo, sd, ed);
        } else if (LikeUserId != null && (ed > 0L && sd > 0L)) {
            //id和日期 都有
            System.out.println("uid = " + LikeUserId + ",sd = " + sd + ",ed= " + ed);
            pageInfo = messageDetailApi.queryPublishByUserIdAndDate(messageParam.getPage(), messageParam.getPagesize(), messageParam.getSortOrder(), LikeUserId, state, sd, ed);
            messagePageResult = this.queryMethod(LikeUserId, state, pagesize, messagePageResult, pageInfo, sd, ed);
        } else if (LikeUserId == null && (ed > 0L && sd > 0L)) {
            //有日期 没id
            System.out.println("uid = " + LikeUserId + ",sd = " + sd + ",ed= " + ed);
            pageInfo = messageDetailApi.queryPublishByDate(messageParam.getPage(), messageParam.getPagesize(), messageParam.getSortOrder(), state, sd, ed);
            messagePageResult = this.queryMethod(LikeUserId, state, pagesize, messagePageResult, pageInfo, sd, ed);
        } else {
            //没日期 没id
            System.out.println("uid = " + LikeUserId + ",sd = " + sd + ",ed= " + ed);
            pageInfo = messageDetailApi.queryAllPublish(messageParam.getPage(), messageParam.getPagesize(), messageParam.getSortOrder(), state);
            messagePageResult = this.queryMethod(LikeUserId, state, pagesize, messagePageResult, pageInfo, sd, ed);
        }
        return messagePageResult;
    }


    private MessagePageResult queryMethod(Integer LikeUserId, String state, Integer pagesize, MessagePageResult messagePageResult, PageInfo<Publish> pageInfo, Long sd, Long ed) {
        List<MessageResult> messageResultList = new ArrayList<>();
        Integer likeCount = 0;
        Integer commentCount = 0;
        Integer reportCount = 0;
        Integer forwardingCount = 0;
        for (Publish publish : pageInfo.getRecords()) {
            MessageResult messageResult = new MessageResult();
            messageResult.setId(publish.getId().toHexString());
            messageResult.setUserId(publish.getUserId().intValue());
            messageResult.setCreateDate(publish.getCreated());
            messageResult.setText(publish.getText());
            messageResult.setMedias(publish.getMedias());
            messageResult.setState(publish.getState());
            messageResult.setTopState(publish.getTopState());

            List<Comment> comments = messageDetailApi.queryPublishComment(publish.getId().toString());
            for (Comment comment : comments) {
                if(publish.getId().equals(comment.getPublishId())&&comment.getCommentType()==1){
                    likeCount++;
                }
                if(publish.getId().equals(comment.getPublishId())&&comment.getCommentType()==2){
                    commentCount++;
                }
                if(publish.getId().equals(comment.getPublishId())&&comment.getCommentType()==4){
                    reportCount++;
                }
                if(publish.getId().equals(comment.getPublishId())&&comment.getCommentType()==5){
                    forwardingCount++;
                }
            }
            messageResult.setLikeCount(likeCount);
            messageResult.setCommentCount(commentCount);
            messageResult.setForwardingCount(forwardingCount);
            messageResult.setReportCount(reportCount);

            //通过userInfo拿到用户的基本信息
            //  将nickname和userLogo给medias给messageDetailVo返回对象
            QueryWrapper<UserInfo> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", publish.getUserId());
            UserInfo userInfo = userInfoMapper.selectOne(queryWrapper);

            messageResult.setUserId(publish.getUserId().intValue());
            messageResult.setNickName(userInfo.getNickName());
            messageResult.setUserLogo(userInfo.getLogo());


            messageResultList.add(messageResult);
        }


        List<Totals> totalsList = new ArrayList<>();
        //待审核的动态状态信息
        Totals totals2 = new Totals();
        totals2.setTitle("待审核");
        totals2.setCode("3");
        totals2.setValue(messageDetailApi.queryCheck(LikeUserId,sd,ed).size());
        totalsList.add(totals2);
        //已通过的动态状态信息
        Totals totals3 = new Totals();
        totals3.setTitle("已拒绝");
        totals3.setCode("4");
        totals3.setValue(messageDetailApi.queryReject(LikeUserId,sd,ed).size());
        totalsList.add(totals3);
        //已驳回的动态状态信息
        Totals totals4 = new Totals();
        totals4.setTitle("已通过");
        totals4.setCode("5");
        totals4.setValue(messageDetailApi.queryPass(LikeUserId,sd,ed).size());
        totalsList.add(totals4);
        //标题全部动态信息
        Totals totals1 = new Totals();
        totals1.setTitle("全部");
        totals1.setCode("all");
        totals1.setValue(totals2.getValue() + totals3.getValue() + totals4.getValue());
        totalsList.add(totals1);

        if (StrUtil.equals(state, "3")) {
            messagePageResult.setPages(totals2.getValue() / pagesize);
            messagePageResult.setCounts(totals2.getValue());
        } else if (StrUtil.equals(state, "4")) {
            messagePageResult.setPages(totals3.getValue() / pagesize);
            messagePageResult.setCounts(totals3.getValue());
        } else if (StrUtil.equals(state, "5")) {
            messagePageResult.setPages(totals4.getValue() / pagesize);
            messagePageResult.setCounts(totals4.getValue());
        }else{
            messagePageResult.setPages(totals1.getValue()/pagesize);
            //获取总条数
            messagePageResult.setCounts(totals1.getValue());
        }

        messagePageResult.setItems(messageResultList);
        messagePageResult.setTotals(totalsList);
        return messagePageResult;
    }


}
